/*
 * $Id: ResourceBundleMessageService.java 42 2013-04-17 15:33:59Z gabakyan $
 * $Author: gabakyan $
 * $Revision: 42 $
 * $Date: 2013-04-17 15:33:59 +0000 (Wed, 17 Apr 2013) $
 *
 * Copyright (c) 2013 Supply Chain Intelligence (SCI), Inc.
 * http://www.scintelligence.com/, Email: info@scintelligence.com
 * All rights reserved.
 *
 * This file is part of Logistics Map.
 *
 * Logistics Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * Logistics Map is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Logistics Map.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.sci.logisticsmap.service;

import com.sci.logisticsmap.data.model.ResourceBundleMessageModel;
import com.sci.logisticsmap.data.repository.ResourceBundleMessageRepository;
import com.sci.logisticsmap.data.support.sorting.ResourceBundleMessageModelSorting;
import com.sci.logisticsmap.service.support.MyReloadableResourceBundleMessageSource;
import com.sci.logisticsmap.service.support.ServiceException;
import com.sci.logisticsmap.service.support.comparator.ResourceBundleMessageLightDTModelCodeComparator;
import com.sci.logisticsmap.service.model.ResourceBundleMessageDTCommand;
import com.sci.logisticsmap.service.model.ResourceBundleMessageLightDTModel;
import com.sci.logisticsmap.support.Constants;
import com.sci.logisticsmap.support.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * The Service for working with Resource bundle message model.
 *
 * @author gabakyan@gmail.com (Last modified by $Author: gabakyan $)
 * @version $Revision: 42 $
 */
@Service
@Transactional
public class ResourceBundleMessageService extends BaseService {
    /**
     * The resource bundle message repository.
     */
    @Autowired
    private ResourceBundleMessageRepository resourceBundleMessageRepository;

    /**
     * The message source.
     */
    @Autowired
    private MyReloadableResourceBundleMessageSource messageSource;

    /**
     * The resource bundle message light model code comparator.
     */
    @Autowired
    private ResourceBundleMessageLightDTModelCodeComparator resourceBundleMessageLightDTModelCodeComparator;

    /**
     * Initializes the edited messages.
     */
    public void initializeEditedMessages() {
        try {
            messageSource.setEditedMessages(getEditedMessages());
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * Edits the resource bundle message.
     *
     * @param command The resource bundle message command.
     */
    public void edit(ResourceBundleMessageDTCommand command) {
        try {
            //Locale locale = Locale.getDefault();

            ResourceBundleMessageModel message = resourceBundleMessageRepository.findOne(command.getCode());
            if (message == null) {
                message = new ResourceBundleMessageModel();
            }
            translationUtilities.translate(command, message);

            resourceBundleMessageRepository.save(message);

            Map<Locale, Map<String, String>> editedMessages = messageSource.getEditedMessages();
            updateEditedMessages(editedMessages, message);

            logger.debug("ResourceBundleMessage saved successfully");
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * Retrieves the resource bundle message light model page.
     *
     * @param page The page number.
     *
     * @return The resource bundle message light model page.
     */
    public Page<ResourceBundleMessageLightDTModel> getLightDTModels(int page) {
        return getLightDTModels(page, Constants.DEFAULT_PAGE_SIZE, null);
    }

    /**
     * Retrieves the resource bundle message light model page.
     *
     * @param page The page number.
     * @param pageSize The page size.
     *
     * @return The resource bundle message light model page.
     */
    public Page<ResourceBundleMessageLightDTModel> getLightDTModels(int page, int pageSize) {
        return getLightDTModels(page, pageSize, null);
    }

    /**
     * Retrieves the resource bundle message light model page.
     *
     * @param page The page number.
     * @param keyword The keyword.
     *
     * @return The resource bundle message light model page.
     */
    public Page<ResourceBundleMessageLightDTModel> getLightDTModels(int page, String keyword) {
        return getLightDTModels(page, Constants.DEFAULT_PAGE_SIZE, null);
    }

    /**
     * Retrieves the resource bundle message light model page.
     *
     * @param page The page number.
     * @param pageSize The page size.
     * @param keyword The keyword.
     *
     * @return The resource bundle message light model page.
     */
    public Page<ResourceBundleMessageLightDTModel> getLightDTModels(int page, int pageSize, String keyword) {
        try {
            Locale locale = Locale.getDefault();

            Map<String, String> originalMessages = messageSource.getOriginalMessages(locale);
            if (originalMessages != null) {
                List<ResourceBundleMessageLightDTModel> messages = new ArrayList<ResourceBundleMessageLightDTModel>();

                Map<String, String> editedMessages = messageSource.getEditedMessages(locale);

                for (String code : originalMessages.keySet()) {
                    String message;
                    if (editedMessages == null || (message = editedMessages.get(code)) == null) {
                        message = originalMessages.get(code);
                    }
                    messages.add(createLightResourceBundleMessage(code, message));
                }
                Collections.sort(messages, resourceBundleMessageLightDTModelCodeComparator);

                int fromIndex = (page - 1) * pageSize;
                int toIndex = Math.min(fromIndex + pageSize, messages.size());

                if (fromIndex < messages.size()) {
                    return new Page<ResourceBundleMessageLightDTModel>(messages.subList(fromIndex, toIndex), page, pageSize, messages.size());
                }
            }

            return null;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * Retrieves the resource bundle message command.
     *
     * @param code The message code.
     *
     * @return The resource bundle message command.
     */
    public ResourceBundleMessageDTCommand getDTCommand(String code) {
        try {
            Locale locale = Locale.getDefault();

            String message = messageSource.getEditedMessage(code, locale);
            if (message == null) message = messageSource.getOriginalMessage(code, locale);

            if (message != null) {
                return createResourceBundleMessageCommand(code, message);
            }
            return null;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * Retrieves the edited messages.
     *
     * @return The edited messages.
     */
    public Map<Locale, Map<String, String>> getEditedMessages() {
        try {
            List<ResourceBundleMessageModel> messages = resourceBundleMessageRepository.findAll(ResourceBundleMessageModelSorting.BY_LOCALE_AND_CODE);
            if (messages != null) {
                Map<Locale, Map<String, String>> editedMessages = new HashMap<Locale, Map<String, String>>();
                for (ResourceBundleMessageModel message : messages) {
                    updateEditedMessages(editedMessages, message);
                }
                return editedMessages;
            }
            return null;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * Updates the edited messages.
     *
     * @param editedMessages The edited messages.
     * @param message The resource bundle message.
     */
    private void updateEditedMessages(Map<Locale, Map<String, String>> editedMessages, ResourceBundleMessageModel message) {
        Locale locale = (
                message.getLanguage() != null ? (
                        message.getCountry() != null ? (
                                message.getVariant() != null ? new Locale(message.getLanguage(), message.getCountry(), message.getVariant())
                                        : new Locale(message.getLanguage(), message.getCountry()))
                                : new Locale(message.getLanguage()))
                        : null);
        //logger.debug("updateEditedMessages: code = {}, message = {}, locale = {{}, {}, {}}", message.getCode(),
        //        message.getMessage(), message.getLanguage(), message.getCountry(), message.getVariant());

        Map<String, String> codeToMessageMap;
        if ((codeToMessageMap = editedMessages.get(locale)) == null) {
            codeToMessageMap = new HashMap<String, String>();
            editedMessages.put(locale, codeToMessageMap);
        }
        codeToMessageMap.put(message.getCode(), message.getMessage());
    }

    /**
     * Creates the resource bundle message light model.
     *
     * @param code The message code.
     * @param messageString The message string.
     *
     * @return The resource bundle message light model.
     */
    private ResourceBundleMessageLightDTModel createLightResourceBundleMessage(String code, String messageString) {
        ResourceBundleMessageLightDTModel message = new ResourceBundleMessageLightDTModel();
        message.setCode(code);
        message.setMessage(messageString);
        return message;
    }

    /**
     * Creates the resource bundle message command.
     *
     * @param code The message code.
     * @param messageString The message string.
     *
     * @return The resource bundle message command.
     */
    private ResourceBundleMessageDTCommand createResourceBundleMessageCommand(String code, String messageString) {
        ResourceBundleMessageDTCommand command = new ResourceBundleMessageDTCommand();
        command.setCode(code);
        command.setMessage(messageString);
        return command;
    }
}
